<template>
  <!--购物车-->
  <div class="cart-container">
    <!-- 顶部流程图 -->
    <div class="flow-chart">
      <img v-if="userLanguage.code == 'zh_CN'" src="@/assets/images/icons/user_car.png" class="flow-img" alt="">
      <img v-else src="@/assets/images/icons/user_car.png" class="flow-img" alt="">
    </div>

    <div class="cart-title">All Products ({{ goodsList.length }})</div>
    <Divider class="title-divider" />
    <div class="cart-content">


      <div class="cart-table-header">
        <div class="item" style="flex:1;">
          Product Details
        </div>
        <div class="item text-center" style="width:140px;">
          Unit Price
        </div>
        <div class="item text-center" style="width:140px;">
          Amount
        </div>
        <div class="item text-center" style="width:100px;">
          Quantity
        </div>
        <div class="item text-center" style="width:100px;">
          Remark
        </div>
        <div class="item text-center" style="width:100px;">
          Operate
        </div>
      </div>

      <div class="cart-empty" v-if="!cartLoading && goodsList.length == 0">
        <t-no-data type="cart"></t-no-data>
      </div>

      <div class="cart-table-body" v-if="goodsList.length > 0">
        <div class="shop-card" v-for="shop in goodsList" :key="shop.id">
          <div class="shop-header">
            <Checkbox class="shop-checkbox" v-model="shop.allActive" @on-change="storeAll">
              <t-platform class="platform-icon" :type="shop.channel"></t-platform>
              <span class="shop-name">{{ shop.shopName }}</span>
            </Checkbox>
          </div>

          <div class="shop-product-list" v-for="product in shop.itemList" :key="product.id">
            <div class="item" style="flex:1;">
              <div class="product-info">
                <Checkbox v-model="product.active" @on-change="onSelectGoods" class="product-checkbox"></Checkbox>

                <div class="product-image">
                  <product-picture :image-list="[product.mainImg]"></product-picture>
                </div>
                <div class="product-details">
                  <router-link
                    :to="`/goods/details?id=${product.spuNo}&channel=${product.channel}` + (userInfo.inviteCode ? `&inviteCode=${userInfo.inviteCode}` : '')"
                    class="product-title">
                    {{ product.subject }}
                  </router-link>

                  <div class="product-attributes">
                    <div v-for="attr in product.skuAttrEnumFormatList" :key="attr.id">
                      {{ attr.name }}：{{ attr.value }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="item text-center" style="width:140px;">
              <div class="price-section">
                <div class="price">{{ userInfo.currencySymbol }} {{ product.price }}</div>
                <div class="edit-price" @click="editBtn(product)">
                  <span class="iconfont icon-bianji"></span>
                </div>
              </div>
            </div>
            <div class="item text-center" style="width:140px;">
              <div class="quantity-section">
                <InputNumber @on-change="onCartEdit(product)" :min="product.startQuantity ? product.startQuantity : 1"
                  v-model="product.quantity" controls-outside>
                </InputNumber>
              </div>
            </div>
            <div class="item text-center" style="width:100px; color: #FF186B; font-weight: 700;">
              {{ userInfo.currencySymbol }} {{ product.price | bigTimes(product.quantity) }}
            </div>
            <div class="item text-center" style="width:100px;">
              <div class="remark-section">
                {{ product.remarks }}
                <span @click="onRmk(product)" class="edit-remark iconfont icon-bianji"></span>
              </div>
            </div>
            <div class="item text-center" style="width:100px;">
              <div class="action-section">
                <div class="delete-btn" @click="getCartDeleteBatch(product.id)">
                  {{ $t('user.delete') }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <t-loading class="loading-indicator" v-if="cartLoading"></t-loading>
    </div>

    <edit-desc ref="childRef" @customImg="customImg" @newRemarks="newRemarks" @updateMet="updateMet"></edit-desc>
    <t-edit-price ref="editRef" @changePrice="updateMet" :popPrice="popPrice"></t-edit-price>

    <div class="cart-summary" v-if="goodsList.length > 0">
      <div class="summary-content">
        <div class="total-items">
          <Checkbox class="select-all" @on-change="onAll" v-model="all">
            <span class="select-text">{{ $t('user.selectAll') }}</span>
          </Checkbox>

          <div class="delete-selected" @click="allDelete" :class="selectLength > 0 ? 'active' : ''">
            {{ $t('user.deleteSelected') }}
          </div>
        </div>

        <div class="total-price">
          <div class="price-info">
            <!-- <i18n path="user.selectedGoods">
              <span slot="num" class="selected-count">{{ selectLength }}</span>
            </i18n> -->
            <span class="label">Product Amount</span>
            <span class="amount">{{ userInfo.currencySymbol }} {{ totalPrice }}</span>
          </div>

          <div class="checkout-btn" :loading="loading" @click="onCartBalanceAccounts">
            {{ $t('user.settleAccount') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { cartBalanceAccounts, cartDeleteBatch, cartEdit, cartList } from "@/api/cart";
import { bigPlus, bigTimes } from "@/common/digital-computation";
import TLoading from "@/components/t-loading";
import TNoData from "@/components/t-no-data";
import { mapState } from "vuex";
import ProductPicture from "@/views/main/user/components/product-picture";
import TPlatform from "@/components/t-platform";
import editDesc from './components/edit-desc.vue';
import { list } from "postcss";
import store from "@/store";
import TEditPrice from "@/components/t-edit-price";
import { pointUser } from "@/common/point/api-hook";

export default {
  name: "shopping-cart",
  components: { TPlatform, ProductPicture, TNoData, TLoading, editDesc, TEditPrice },
  data() {
    return {
      infoList: {},
      cartLoading: false,
      loading: false,
      ids: [],
      all: false,
      totalPrice: 0,
      selectLength: 0,
      model1: '',
      rmk: '',
      goodsList: [],
      cityList: [
        {
          value: 'New York',
          label: 'New York'
        },
        {
          value: 'London',
          label: 'London'
        },
      ],
      popPrice: 0,
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      userLanguage: (state) => state.user.userLanguage
    })
  },
  created() {
    this.getCartList();
  },
  methods: {
    editBtn(info) {
      this.$refs.editRef.open(info);
      if (info.manuaPrice) {
        this.popPrice = info.manuaPrice;
      } else if (info.originalPriceCNY) {
        this.popPrice = info.originalPriceCNY;
      }
    },
    customImg(value) {
      this.infoList.imageRemarks = value;
    },
    newRemarks(value) {
      this.infoList.remarks = value;
    },
    updateMet(e) {
      this.onCartEdit(e);
    },
    onCartBalanceAccounts() {
      if (this.$analytics) {
        this.$analytics.logEvent('carCreateOrder');
      }

      this.ids = [];
      this.goodsList.forEach(item => {
        item.itemList.forEach(listItem => {
          if (listItem.active) {
            this.ids.push(listItem.id)
          }
        })
      })

      if (this.ids.length <= 0) {
        this.$Message.error(this.$t('user.pleaseSelectProduct'));
        return false;
      }

      this.loading = true;
      cartBalanceAccounts(this.ids).then((res) => {
        pointUser('actions', '2006');
        this.$store.commit('removeCartNum', this.ids.length);
        this.loading = false;
        this.$router.push(`/confirm/order?id=${res.result}`);
      }).catch(() => {
        this.loading = false;
      })
    },
    storeAll() {
      this.goodsList.forEach(item => {
        if (item.allActive) {
          item.itemList.forEach(subItem => {
            subItem.active = true;
          })
        } else {
          item.itemList.forEach(subItem => {
            subItem.active = false;
          })
        }
      })
      this.onSelectGoods();
    },
    onAll() {
      if (this.all) {
        this.goodsList.forEach(item => {
          item.allActive = true;
          item.itemList.forEach(listItem => {
            listItem.active = true;
          })
        })
      } else {
        this.goodsList.forEach(item => {
          item.allActive = false;
          item.itemList.forEach(listItem => {
            listItem.active = false;
          })
        })
      }
      this.onSelectGoods();
    },
    onRmk(info) {
      this.infoList = info;
      this.$refs.childRef.open(info);
    },
    allDelete() {
      this.ids = [];
      this.goodsList.forEach(item => {
        item.itemList.forEach(listItem => {
          if (listItem.active) {
            this.ids.push(listItem.id)
          }
        })
      })
      if (this.ids.length > 0) {
        this.getCartDeleteBatch();
      }
    },
    onSelectGoods() {
      this.totalPrice = 0;
      this.selectLength = 0;
      this.goodsList.forEach(item => {
        item.itemList.forEach(listItem => {
          if (listItem.active) {
            this.selectLength = this.selectLength + 1;
            let t = bigTimes(listItem.price, listItem.quantity);
            this.totalPrice = bigPlus(this.totalPrice, t);
          }
        })
      })

      this.goodsList.forEach(item => {
        const subActiveCheck = item.itemList.every(subItem => subItem.active);
        if (subActiveCheck) {
          item.allActive = true;
        } else {
          item.allActive = false;
        }
      })

      const allActiveCheck = this.goodsList.every(item => item.allActive && item.itemList.every(subItem => subItem.active));
      if (allActiveCheck) {
        this.all = true;
      } else {
        this.all = false;
      }
    },
    getCartDeleteBatch(id) {
      let cardIds = [];
      if (id) {
        cardIds = [id];
      } else {
        cardIds = this.ids;
      }

      cartDeleteBatch(cardIds).then(() => {
        this.$store.commit('removeCartNum', cardIds.length);
        this.$Message.success(this.$t('user.successfullyDeleted'));
        this.ids = '';
        this.getCartList();
      })
    },
    onCartEdit(info) {
      this.onSelectGoods();
      cartEdit({
        channel: info.channel,
        id: info.id,
        remarks: info.remarks,
        spuNo: info.spuNo,
        quantity: info.quantity,
        skuNo: info.skuNo,
        imageRemarks: info.imageRemarks,
        manuaAdjustRemark: info.manuaAdjustRemark,
        manuaPrice: info.manuaPrice,
        manuaAdjustImage: info.manuaAdjustImage
      }).then((res) => {
        if (res.code == 200) {
          this.descPopup = false;
          this.getCartList();
        }
      });
    },
    getCartList() {
      this.cartLoading = true;
      cartList().then((res) => {
        this.cartLoading = false;
        let data = res.result.shopList;
        data.forEach(item => {
          item.allActive = false;
          item.itemList.forEach(listItem => {
            listItem.active = false;
          })
        })
        this.goodsList = data;
      }).catch(() => {
        this.cartLoading = false;
      })
    }
  }
}
</script>

<style scoped lang="less">
.cart-container {
  width: 100%;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 20px;
  padding: 20px;

  .title-divider {
    margin-bottom: 10px;
  }

  .flow-chart {
    margin-bottom: 30px;
    border-radius: 8px;
    overflow: hidden;

    img {
      width: 100%;
      display: block;
    }
  }
}

.cart-header {
  margin-bottom: 24px;

  .header-image {
    width: 100%;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.cart-title {
  color: #2F333A;
  font-family: Inter;
  font-size: 24px;
  font-style: normal;
  font-weight: 600;
  line-height: normal;
  margin-bottom: 15px;

}

.cart-content {
  background-color: #fff;
  margin-bottom: 24px;
  overflow-y: auto;
  max-height: 500px;
}

.cart-table-header {
  display: flex;
  gap: 10px;
  height: 35px;
  border-radius: 8px;
  background: #F5F5F5;
  padding-left: 28px;
  margin-bottom: 18px;

  .item {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #969696;
  }

  .text-center {
    justify-content: center;
  }
}

.shop-card {
  margin-bottom: 18px;
  border-bottom: 1px solid #e9ecef;
  overflow: hidden;
  padding-bottom: 18px;

  &:last-child {
    margin-bottom: 0;
  }
}

.shop-header {
  padding: 12px 0;

  .shop-checkbox {
    display: flex;
    align-items: center;

    .platform-icon {
      margin-right: 8px;
      margin-left: 12px;

      /deep/ .icon-image {
        margin-top: 0;
      }
    }

    .shop-name {
      font-weight: 600;
      font-size: 14px;
      color: #2F333A;
    }
  }
}

.shop-product-list {
  display: flex;
  gap: 10px;

  .item {
    display: flex;
    align-items: center;
  }

  .text-center {
    justify-content: center;
  }

  .quantity-section {
    /deep/ .ivu-input-number-input {
      text-align: center;
    }
  }
}

.product-list {
  padding: 0 16px;
}

.product-item {
  display: flex;
  flex-direction: column;
  padding: 16px 0;
  border-bottom: 1px solid #f1f1f1;

  &:last-child {
    border-bottom: none;
  }
}

.product-info {
  display: flex;
  margin-bottom: 12px;
  align-items: center;

  .product-checkbox {
    margin-right: 12px;
  }

  .product-image {
    width: 80px;
    height: 80px;
    margin-right: 16px;
    border-radius: 4px;
    overflow: hidden;

    /deep/ .product-picture {
      width: 100%;
      height: 100%;
      display: block;
    }
  }

  .product-details {
    flex: 1;

    .product-title {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      margin-bottom: 6px;
      display: block;
      text-decoration: none;

      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      /* 限制显示行数 */
      overflow: hidden;
      text-overflow: ellipsis;

      &:hover {
        color: #FF186B;
      }
    }

    .product-attributes {
      font-size: 12px;
      color: #969696;
    }
  }
}

.price-section {
  display: flex;
  align-items: center;

  .price {
    color: #969696;
  }

  .edit-price {
    margin-bottom: 4px;
    cursor: pointer;
    margin-left: 10px;

    .iconfont {
      font-size: 13px;
    }

    &:hover {
      text-decoration: underline;
    }
  }
}

.remark-section {
  color: #666;
  font-size: 14px;

  .edit-remark {
    margin-left: 8px;
    color: #969696;
    cursor: pointer;
  }
}

.action-section {
  .delete-btn {
    color: #969696;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
      color: #FF186B;
    }
  }
}

.product-actions {
  display: flex;
  align-items: center;
  padding-left: 28px;

  >div {
    flex: 1;
    text-align: center;
  }



  .quantity-section {
    /deep/ .ivu-input-number {
      width: 100px;
      text-align: center;
    }

    /deep/ .ivu-input-number-input {
      text-align: center;
    }
  }

  .total-section {
    font-weight: 600;
    color: #333;
  }


}

.loading-indicator {
  margin: 40px 0;
}

.cart-summary {
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.summary-content {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .total-items {
    display: flex;
    align-items: center;

    .select-all {
      margin-right: 24px;

      .select-text {
        font-weight: 500;
        margin-left: 5px;
      }
    }

    .delete-selected {
      color: #999;
      cursor: pointer;

      &.active {
        color: #f56c6c;
      }

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .total-price {
    display: flex;
    align-items: center;

    .price-info {
      margin-right: 24px;


      .selected-count {
        color: #1890ff;
        font-weight: 600;
      }

      .label {
        display: block;
        color: #969696;
        font-size: 14px;
        line-height: 14px;
      }

      .amount {
        color: #FF186B;
        font-weight: 600;
        font-size: 24px;
        margin-left: 12px;
        display: block;
        text-align: right;
      }
    }

    .checkout-btn {
      border-radius: 6px;
      background: #FF186B;
      color: #fff;
      padding: 12px 32px;
      border-radius: 4px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s;
      width: 320px;
      height: 50px;
      text-align: center;
    }
  }
}
</style>